import java.awt.Dimension;
import java.awt.Point;
import java.awt.Rectangle;
import java.util.ArrayList;

public class CollisionDetector {
	
	private Map map;
	
	public CollisionDetector(Map map) {
		this.map = map;
	}
	
	/**
	 * Detects if User or a monsters is affected by an exploded bomb
	 */
	public void detectBombEntityCollision() {
		
		// Check if there is a bomb explosion, if not return immediately
		if (map.getExplodingBlocks().size() == 0) {
			return;
		}
				
		// Detect User bomb collision
		for (Block block : map.getExplodingBlocks()) {
			if (getRectangle(map.getUser()).intersects(getRectangle(block))) {
				map.handleUserBombCollision();
				break;
			}
		}
		
		// Detect Monster bomb collision
		ArrayList<Monster> deadMonsters = new ArrayList<Monster>(); 
		
		for (Block block : map.getExplodingBlocks()) {
			for (Monster monster : map.getMonsters()) {
				if (getRectangle(block).intersects(getRectangle(monster))) {
					deadMonsters.add(monster);
				}
			}
		}
		
		map.handleMonsterBombCollision(deadMonsters);
	}
	
	/**
	 * Detects if User encounters any monster
	 */
	public void detectUserMonsterCollision() {
		for (Monster monster : map.getMonsters()) {
			if (getRectangle(monster).intersects(getRectangle(map.getUser()))) {
				map.handleUserMonsterCollision();
				break;
			}
		}
	}
	
	private Rectangle getRectangle(Entity entity) {
		return new Rectangle(new Point(entity.getX(), entity.getY()), 
                new Dimension(Entity.getEntityWidth(), Entity.getEntityHeight()));
	}
}
